package com.demo.mybatis.executor.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.demo.mybatis.CConfigeration;
import com.demo.mybatis.entity.User;
import com.demo.mybatis.executor.CExecutor;

public class SimpleExecutor implements CExecutor{

	public <E> E query(String sql, Object parameter) {
		try{
		 Connection conn = getConnection();
	     PreparedStatement pstmt;
	     pstmt = conn.prepareStatement(String.format(sql, Integer.parseInt(String.valueOf(parameter))));
	     ResultSet rs = pstmt.executeQuery();
	     User user = new User();
	     while (rs.next()) {
	    	 user.setId(rs.getString(1));
	    	 user.setUserName(rs.getString(2));
	    	 user.setPassWord(rs.getString(3));
	    	 user.setAge(rs.getString(4));
	     }
	     return (E) user;
	 } catch (SQLException e) {
	     e.printStackTrace();
	 }

	 return null;
	}
	

	public Connection getConnection() throws SQLException {
	    String driver = CConfigeration.loadConfigXML().getDriver();
	    String url = CConfigeration.loadConfigXML().getUrl();
	    String username = CConfigeration.loadConfigXML().getUsername();
	    String password = CConfigeration.loadConfigXML().getPassword();
	    Connection conn = null;
	    try {
	        Class.forName(driver); //classLoader,加载对应驱动
	        conn = DriverManager.getConnection(url, username, password);
	    } catch (ClassNotFoundException e) {
	        e.printStackTrace();
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }
	    return conn;
	}





}
